package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.util.StringUtil;
import team.bluepen.supermarket.web.base.DataServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 商品删除
 * @author Kai
 */
@WebServlet(name = "GoodDeleteServlet", urlPatterns = "/api/good-delete")
public class GoodDeleteServlet extends DataServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        if (!checkUserRole(req)) {
            resp.sendRedirect(requestSource);
            return;
        }
        String row = req.getParameter(Constant.GOOD_ROW_PARAM);
        String type = req.getParameter("type");
        if (StringUtil.isEmpty(type)) {
            resp.sendRedirect(requestSource);
            return;
        }


        if ("all".equalsIgnoreCase(type)) {
            Error error = goodRepository.delete();
            resp.sendRedirect(requestSource + "?error=" + error.getValue());
        } else if ("good".equalsIgnoreCase(type)) {
            if (row == null) {
                resp.sendRedirect(requestSource + "?error=" + Error.ERROR_NULL.getValue());
                return;
            }

            Error error = goodRepository.delete(row);
            resp.sendRedirect(requestSource + "?error=" + error.getValue());
        } else {
            resp.sendRedirect(requestSource + "?error=" + Error.ERROR_DATABASE.getValue());
        }

    }
}
